package com.zhn.usermanager.service.impl;

import com.zhn.usermanager.mapper.PictureUploadMapper;
import com.zhn.usermanager.pojo.User;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 头像上传
 */
@Service
public class PictureUploadServiceImpl {

    @Resource
    private PictureUploadMapper pictureUploadMapper;

    public Map<String, Object> pictureUpload(MultipartFile file, HttpServletRequest request) throws IOException {
        Map<String, Object> map = new HashMap<>();
        String abPath = "upload";
        String uploadPath = request.getServletContext().getRealPath("") + File.separator + abPath + File.separator;   // 得到相当项目工程的硬盘物理地址
        String fileName = file.getOriginalFilename();                   // 获取上传的文件名
        File newFile = new File(uploadPath + fileName);         // 根据当前工程的物理路径+文件名生成一个file对象
//        System.out.println("newFile=" + newFile);
        FileCopyUtils.copy(file.getBytes(), newFile);                   // 通过上传通道中的字节码完成file文件的写入操作
        User user = (User)request.getSession().getAttribute("user");
        String userSQLPath = File.separator + abPath + File.separator + fileName;  // 组装一个浏览器识别的文件地址
//        System.out.println("header=" + userSQLPath);
        pictureUploadMapper.pictureUpload(userSQLPath, "" + user.getId());
        map.put("code", 200);
        map.put("msg", "上传头像成功");
        map.put("data", userSQLPath);
        return map;
    }
}
